from rest_framework import serializers
from .models import OAuthQQUser
from users.models import User
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings


class QQRegisterSerializer(serializers.Serializer):
    access_token = serializers.CharField(label='操作token')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[345789]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6)

    def validate(self, attrs):
        # 从请求中获取access_token
        access_token = attrs.get('access_token')
        # 通过OAuthQQUser类中的解密openid的方法获取openid明文
        openid = OAuthQQUser.check_save_user_token(access_token)
        attrs['openid'] = openid
        # 验证短信码
        ## 获取请求中的手机号码
        mobile = attrs.get('mobile')
        ## redis连接code设置
        redis_conn = get_redis_connection('code')
        ## 获取redis中存放的手机验证码
        redis_code = redis_conn.get('sms_%s' % mobile)
        ## 验证码是否相符
        if redis_code.decode() != attrs['sms_code']:
            raise serializers.ValidationError('验证码错误')
        # 判断手机号是否被注册(即 是否是注册用户)
        try:
            ## 根据手机号获取用户
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            ## 该手机号已经注册过
            ### 验证用户密码是否正确
            password = attrs.get('password')
            if not user.check_password(password):
                raise serializers.ValidationError('密码错误')

            # 将用户数据保存,以备保存数据使用
            attrs['user'] = user
        return attrs

    def create(self, validated_data):
        user = validated_data.get('user')
        # 用户不存在
        if not user:
            # 在user表中创建user
            user = User.objects.create(
                username=validated_data.get('mobile'),
                password=validated_data.get('password'),
                mobile=validated_data.get('mobile')
            )
            user.set_password(validated_data['password'])
            user.save()
        # 将openid和用户id存入oauthqq的表内
        OAuthQQUser.objects.create(
            openid=validated_data.get('openid'),
            user=user
        )
        # 返回一个user
        return user
